import React, { Component } from 'react';
import { connect } from 'dva';
import { PlusOutlined } from '@ant-design/icons';
import { Card, message, Button, Table, Tag } from 'antd';
import Ellipsis from '../../../components/Ellipsis';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import { getDictOptionsByCode, filterAuth } from '@/support/common';
import moment from 'moment';
import styles from './index.less';
import router from 'umi/router';
import { contentTemplateCopy } from '@/services/contentMng/contentTempList';
import { isJson } from '@/utils/common';
import MaskText from '@/components/MaskText';
const mapStateToProps = (state: any) => ({
  contentMng: state.contentMng,
  menu: state.menu,
  loading: state.loading.models['contentMng'],
});

class ContentTempList extends Component<any, any> {
  constructor(props: any) {
    super(props);
    const contentItemInfoStr = sessionStorage.getItem('contentItemInfo');
    const contentItemInfo = isJson(contentItemInfoStr) ? JSON.parse(contentItemInfoStr!) : {};
    this.state = {
      contentId: contentItemInfo.contentId,
      contentProjetId: contentItemInfo.projectId,
      formValues: {},
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'contentMng/queryTempList',
      payload: { contentItemSid: this.state.contentId },
    });
    dispatch({
      type: 'contentMng/queryTagList',
      payload: { contentItemSid: this.state.contentId },
    });
    // /**获取key列表 */
    // dispatch({
    //   type: 'contentMng/queryKeyList',
    //   payload: {},
    // });
  }
  handleFlushPage = () => {
    const {
      contentMng: {
        contentTempData: { pagination },
      },
      dispatch,
    } = this.props;
    const { current, pageSize } = pagination;
    const { formValues } = this.state;
    const params = {
      ...formValues,
      contentItemSid: this.state.contentId,
      current: current,
      pageSize: pageSize,
    };
    dispatch({
      type: 'contentMng/queryTempList',
      payload: { ...params },
    });
    dispatch({
      type: 'contentMng/queryTagList',
      payload: { contentItemSid: this.state.contentId },
    });
  };
  /**
   * 处理默认入参
   */
  handleRestParams = (fields: any) => {
    fields['contentItemSid'] = this.state.contentId;
    return fields;
  };
  // 分页时触发
  tableOnChange = (pagination: any) => {
    const { dispatch } = this.props;
    const current = pagination.current;
    const { formValues } = this.state;
    const params = {
      ...formValues,
      contentItemSid: this.state.contentId,
      current: current,
      pageSize: pagination.pageSize,
    };
    dispatch({
      type: 'contentMng/queryTempList',
      payload: { ...params },
    });
  };
  handleAdd = () => {
    const tempInfo = {
      tempId: null,
      isEdit: true,
      data: null,
    };
    sessionStorage.setItem('tempInfo', JSON.stringify(tempInfo));
    router.push('/contentMng/contentTempDetail');
  };
  handleMng = (record: any) => {
    const templateConfig = JSON.parse(record.templateConfig);
    // 内容项中涉及到图片，且图片是必填字段，且只有一个图片字段时则第一栏展示图片缩略图
    const imageTempSet = templateConfig.filter((config: any) => {
      return config.type == 3;
    });
    const isUniqImgConfig =
      !!imageTempSet &&
      imageTempSet.length === 1 &&
      !!imageTempSet.find((imageConfig: any) => imageConfig['is_require'] === 1);
    sessionStorage.setItem('tempId', record.sid);
    sessionStorage.setItem('touchWayCode', record.touchWayCode);
    sessionStorage.setItem('isUniqImgConfig', JSON.stringify(isUniqImgConfig));
    sessionStorage.setItem('tempConfig', record.templateConfig);
    if (record.dirConfig) {
      let { sid, touchWayCode } = record;
      sessionStorage.setItem('dirConfig', record.dirConfig);
      sessionStorage.setItem(
        'contentListInfo',
        JSON.stringify({
          tempId: sid,
          touchWayCode,
          isUniqImgConfig,
          contentId: this.state.contentId,
          contentProjetId: this.state.contentProjetId,
        }),
      );
    }
    router.push({
      pathname: !!record.dirConfig ? '/contentMng/contentDirectory' : '/contentMng/contentList',
      query: { tempId: record.sid },
    });
  };

  handleView = (record: any) => {
    const tempInfo = {
      tempId: record.sid,
      isEdit: false,
      data: record,
    };
    sessionStorage.setItem('tempInfo', JSON.stringify(tempInfo));
    router.push('/contentMng/contentTempDetail');
  };

  handleEdit = (record: any) => {
    const tempInfo = {
      tempId: record.sid,
      isEdit: true,
      data: record,
    };
    sessionStorage.setItem('tempInfo', JSON.stringify(tempInfo));
    router.push('/contentMng/contentTempDetail');
  };
  handleDelete = (sid: string) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'contentMng/delTempItem',
      payload: { sid },
      callback: (res: any) => {
        message.success('删除成功！');
        this.handleFlushPage();
      },
    });
  };

  // 复制全部内容
  copyContent = (record: any) => {
    sessionStorage.setItem(
      'contentCopyInfo',
      JSON.stringify({
        type: 'copyAll',
        data: record,
      }),
    );
    message.success('已复制该模板下全部内容，可在新建目录或内容时粘贴');
  };

  handleBack() {
    sessionStorage.removeItem('contentId');
    router.push('/contentMng/contentMngList');
  }
  render() {
    const {
      menu: { permissions, dicData },
      location: { pathname = '/' },
      contentMng: {
        contentTempData: { contentTempList, pagination },
        labelList,
      },
      loading,
    } = this.props;
    const { formValues } = this.state;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const displayTerminalOptions = getDictOptionsByCode(dicData, 'displayTerminalOptions');
    const touchWayOptions = getDictOptionsByCode(dicData, 'touchWayCode');
    const searchItems = [
      {
        type: 'input',
        title: '模板ID',
        key: 'templateCode',
      },
      {
        type: 'input',
        title: '模版名称',
        key: 'templateName',
      },
      {
        type: 'select',
        title: '展现终端',
        key: 'displayTerminalCode',
        showSearch: false,
        selectOptions: displayTerminalOptions,
      },
      {
        type: 'select',
        title: '触达方式',
        key: 'touchWayCode',
        showSearch: false,
        selectOptions: touchWayOptions,
      },
      {
        type: 'select',
        title: '标签内容',
        key: 'labelContent',
        showSearch: true,
        selectOptions: labelList,
      },
    ];
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        width: 60,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: '模板ID',
        dataIndex: 'templateCode',
      },
      {
        title: '模版名称',
        dataIndex: 'templateName',
        render: (text: any) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '展现终端',
        dataIndex: 'displayTerminalCode',
        render: (text: any) =>
          displayTerminalOptions.find(item => {
            return item.value == text;
          })?.label,
      },
      {
        title: '触达方式',
        dataIndex: 'touchWayCode',
        render: (text: any) =>
          touchWayOptions.find(item => {
            return item.value == text;
          })?.label,
      },
      {
        title: '内容形式',
        dataIndex: 'contentformStr',
        width: 215,
        render: (text: any) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '标签内容',
        dataIndex: 'labelContent',
        render: (text: any) => {
          if (text) {
            const labelTextArray = text?.split(';');
            const labelTextLength = labelTextArray[0]?.length + 1 + labelTextArray[1]?.length + 1;
            return (
              <Ellipsis length={labelTextLength} tooltip>
                {text}
              </Ellipsis>
            );
          } else {
            return '';
          }
        },
        // render: (text: any, record: any) => {
        //   if (text) {
        //     const labelTextArray = text.split(';');
        //     return labelTextArray.map((item: any, index: any) => (
        //       <Tag color="purple" key={record.templateCode + 'temp' + index}>
        //         {item}
        //       </Tag>
        //     ));
        //   } else {
        //     return text;
        //   }
        // },
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 185,
        render: (text: any) => {
          return moment(text).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        render(val: any) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        width: 185,
        render: (text: any) => {
          return text && moment(text).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '更新人',
        dataIndex: 'updateBy',
        render(val: any) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        fixed: 'right',
        render: (text: any, record: any) => {
          //  内容项模版中的内容全部没有发布，则该内容项可以被删除；
          //  如果没有关联内容(hasContent !== 1)，则可以编辑模板
          // 否则只能查看详情
          const btnsFilter =
            record.hasPublished === 1
              ? ['mng', 'detail']
              : record.hasContent !== 1
              ? ['mng', 'edit', 'del']
              : ['mng', 'detail', 'del'];
          const btnsArray = [
            {
              title: '内容管理',
              key: 'mng',
              auth: 'contentTemp_doMng',
              onConfirm: () => this.handleMng(record),
            },
            {
              title: '编辑',
              key: 'edit',
              auth: 'contentTemp_doEdit',
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: '详情',
              key: 'detail',
              auth: 'contentTemp_doView',
              onConfirm: () => this.handleView(record),
            },
            {
              title: '删除',
              key: 'del',
              auth: 'contentTemp_doDel',
              message: '是否确认删除？',
              Popconfirm: true,
              onConfirm: () => this.handleDelete(record.sid),
            },
          ];
          const btns = btnsArray.filter(item => {
            return btnsFilter.indexOf(item.key) > -1;
          });
          const copyBtn =
            record.hasContent === 1 || record.hasDirectory === 1
              ? [
                  {
                    title: '复制全部内容',
                    key: 'copy',
                    auth: 'contentTemp_doDel',
                    onConfirm: () => this.copyContent(record),
                  },
                ]
              : [];
          return <PateoAuthButtons pathname={pathname} btns={[...btns, ...copyBtn]} max={2} />;
        },
      },
    ];

    return (
      <div>
        <Card title="" bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{ type: 'contentMng/queryTempList' }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFormReset={() => this.setState({ formValues: {} })}
            handleFieldsValue={this.handleRestParams}
          />
        </Card>
        <Card bordered={false} style={{ marginTop: 12 }}>
          <div className="my_newItem">
            {filterAuth('contentTemp_doAdd', permissions, pathname) && (
              <Button
                onClick={() => this.handleAdd()}
                size="small"
                icon={<PlusOutlined />}
                type="primary"
              >
                新增
              </Button>
            )}
          </div>
          <Table
            className={styles['customer-grid']}
            loading={loading}
            rowKey={(row: { sid: any }) => row.sid}
            columns={columns}
            size="small"
            pagination={paginationProps}
            onChange={this.tableOnChange}
            dataSource={contentTempList}
            scroll={{ x: 'max-content' }}
          />
        </Card>
        <Card bordered={false}>
          <Button onClick={() => this.handleBack()} size="small" type="primary">
            返回
          </Button>
        </Card>
      </div>
    );
  }
}

export default connect(mapStateToProps)(ContentTempList);
